﻿@page "/Admin/MusicManager"
@using JxAudio.Core.Entity
@using Jx.Toolbox.Extensions
@using Microsoft.Extensions.Localization
@using FreeSql
@using JxAudio.Web.Utils
@inject IStringLocalizer<MusicManager> MusicLocalizer

<AdminTable TItem="TrackEntity" ShowToolbar="true" ShowAddButton="false" ShowExtendButtons="true"
            ConfirmDeleteContentText="@MusicLocalizer["DeleteMusicText"]" OnDeleteAsync="OnDeleteAsync">
    <TableColumns>
        <TableColumn @bind-Field="@context.PictureId" Width="50">
            <Template Context="value">
                <Avatar Url="@($"/api/Cover?coverId={value.Value}")"></Avatar>
            </Template>
        </TableColumn>
        <TableColumn @bind-Field="@context.ProviderId" LookupServiceKey="plugin"></TableColumn>
        <TableColumn @bind-Field="@context.FullName"></TableColumn>
        <TableColumn @bind-Field="@context.Title">
            <Template Context="value">
                @if (value.Value.IsNullOrEmpty())
                {
                    @MusicLocalizer["NoTitle"]
                }
                else
                {
                    @value.Value
                }
            </Template>
        </TableColumn>
        <TableColumn @bind-Field="@context.Size">
            <Template Context="value">
                @value.Value.ToSizeString()
            </Template>
        </TableColumn>
        <TableColumn @bind-Field="@context.Duration">
            <Template Context="value">
                @value.Value.ToTimeString()
            </Template>
        </TableColumn>
    </TableColumns>
</AdminTable>

@code {

    private async Task<bool> OnDeleteAsync(IEnumerable<TrackEntity> arg)
    {
        foreach (var trackEntity in arg)
        {
            var provider = Constant.GetProvider(trackEntity.ProviderId);
            if (provider == null || trackEntity.DirectoryEntity == null)
            {
                return false;
            }
            
            await provider.DeleteFiles(trackEntity.DirectoryEntity.Path);
            await BaseEntity.Orm.GetRepository<TrackEntity>().DeleteCascadeByDatabaseAsync(x => x.Id == trackEntity.Id);
        }
        return true;
    }

}